<template>
  <div class="svg-progress">
    <img v-show="songPicUrl"
      class="svg-progress--pic"
      v-lazy="`${songPicUrl}?param=100y100`"
      :src="`${songPicUrl}?param=100y100`"
      alt="song pic">
    <div class="svg-progress--circle">
      <svg viewBox="0 0 30 30" version="1.1" xmlns="http://www.w3.org/2000/svg">
        <circle cx="15" cy="15" :r="r"
          transform="rotate(-90, 15, 15)" fill="none"
          :stroke="stroke" :stroke-width="strokeWidth"
          :stroke-dasharray="dasharray" :stroke-dashoffset="dashoffset"
        />
      </svg>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'svg-progress',
  data () {
    return {
      r: 14,
      stroke: 'rgba(255, 0, 0, .6)',
      strokeWidth: 2,
      ct: 0,
      timer: null
    }
  },
  computed: {
    ...mapGetters(['audio', 'isPlay', 'songDt', 'songPicUrl']),
    dasharray () {
      return 2 * Math.PI * this.r
    },
    dashoffset () {
      return this.ct ? this.dasharray * (1 - this.ct * 1000 / this.songDt) : this.dasharray
    }
  },
  mounted () {
    // this.ct = this.audio.currentTime
    this.isPlay && this.start()
  },
  beforeDestroy () {
    this.stop()
  },
  methods: {
    start () {
      this.stop()
      this.timer = setInterval(() => {
        this.ct = this.audio.currentTime
      }, 1000)
    },
    stop () {
      this.timer && clearInterval(this.timer)
    }
  },
  watch: {
    isPlay (newVal, oldVal) {
      if (newVal) {
        this.start()
      } else {
        this.stop()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.svg-progress {
  position: relative;

  &--pic {
    /* z-index: -1; */
    position: absolute;
    top: .01rem;
    left: .01rem;
    width: .28rem;
    border-radius: 50%;
  }

  &--circle {
    width: 100%;
    height: 100%;
  }
}
</style>
